import {request} from '../../utils/http'

let btnStatus = true

Page({
  data: {
    no:null,
    order_id:null,
    id:null,
    price:null,
    coupon_count:0,
    use_coupon:{
      coupon_received_id: null,
      title:''
    },
    discount_amount:null,
    real_price:null
  },
  onLoad(query:any) {
    
    this.setData({
      no:query.no,
      id:query.id,
      price:query.price,
      real_price:query.price,
      order_id:query.order_id,
    }, () => {
      this.getOrderNum()
    })
  },
  onShow(){
    btnStatus = true
    if (this.data.use_coupon.coupon_received_id) {
      this.getRealPrice()
    }
  },
  getOrderNum(){
    request('/my_coupons','get',{status:0,stage_id:this.data.id}).then(res => {
      if (res.code == 200) {
        this.setData({
          coupon_count:res.data.length
        })
      }
    })
  },
  getRealPrice(){
    request('/discount_amount', 'get', {stage_id:this.data.id,coupon_received_id:this.data.use_coupon.coupon_received_id}).then(res => {
      if (res.code == 200) {
        let discount_amount = Number(res.data.discount_amount)

        this.setData({
          discount_amount,
          real_price:res.data.need_pay_amount
        })
      }
    })  
  },
  goUse(){
    if (this.data.coupon_count == 0) {
      return
    }

    my.navigateTo({
      url:`/pages/use-coupon/use-coupon?stage_id=${this.data.id}`
    })
  },
  submit(){
    if (!btnStatus) {
      return 
    }

    btnStatus = false
    let self = this;
    request(`/order/voluntary_repayment/${this.data.id}`, "post", {
      coupon_received_id:this.data.use_coupon.coupon_received_id
    }).then((res) => {
      btnStatus = true
      if (res.code == 200) {
        let trade_no = res.data.trade_no;
        my.tradePay({
          tradeNO: trade_no,
          success(result:any) {
            if (result.resultCode == '9000') {
              self.getOrderStageStatus();

            } else {
              my.showToast({ content: result.memo });
            }
          },
          fail(error) {
            console.log(error, "error");
          },
        });
      } else {
        my.showToast({ content: res.message });
      }
    });
  },
  getOrderStageStatus() {
    request("/order/stage/pay_result/" + this.data.id, "get", {
      queryStatus: 1,
    }).then((res) => {
      if (res.code == 200) {
        my.redirectTo({
          url: `/pages/pay-result/pay-result?id=${this.data.order_id}&status=${res.data.status}`,
        });
      } else {
        my.showToast({ content: res.message });
      }
    });
  },
});
